package com.ayg.test.apitest.core;

import com.ayg.test.apitest.constants.CasesState;
import com.ayg.test.apitest.constants.SqlString;
import com.ayg.test.apitest.dao.PaymentDao;
import com.ayg.test.apitest.entity.TestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

public class CaseUpdateDbListener extends TestListenerAdapter{
    private static final Logger logger = LoggerFactory.getLogger(CaseUpdateDbListener.class);
    private PaymentDao dao = new PaymentDao();
    private int mCount = 0;

    @Override
    public void onTestFailure(ITestResult tr) {
        log(tr.getName()+ "--Test method failed\n");
        updateTestStatus(tr,CasesState.DEAL_FAIL);
    }

    @Override
    public void onTestSkipped(ITestResult tr) {
        log(tr.getName()+"--Test method skipped\n");
    }

    @Override
    public void onTestSuccess(ITestResult tr) {
        log(tr.getName()+"--Test method success\n");
        updateTestStatus(tr, CasesState.DEAL_SUCCESS);
       // tr.setStatus(ITestResult.FAILURE);
      //  tr.setThrowable(new Throwable("测试出错"));
    }

    @Override
    public void onFinish(ITestContext testContext) {
        log("--Test finish\n");
        int passSize = testContext.getPassedTests().size();
        int failSize = testContext.getFailedTests().size();
        int skipSize = testContext.getSkippedTests().size();
        logger.info("pass:{},fail:{},skip:{}",passSize,failSize,skipSize);
    }
    private void updateTestStatus(ITestResult tr,Integer status) {
        //断言执行完后更新用例状态
        Object[] objects = tr.getParameters();
        for(Object o : objects){
            TestCase testCase  = (TestCase)o;
            logger.info("更新新数据库用例状态:{}",testCase.getId());
            dao.update(SqlString.UPDATE_PAYMENT_TESTCASE_STATUS_SQL,status,testCase.getId());
            log(((TestCase)o).getName());
        }
    }


    private void log(String string) {
        System.out.print(string);
        if (++mCount % 40 == 0) {
            System.out.println("");
        }
    }

}